#include "ti_msp_dl_config.h"

void set_1motorspeed(int speed)
{
    // 限制速度范围
    if (speed > 10000) speed = 10000;
    if (speed < -10000) speed = -10000;
    
    // 控制电机方向和PWM
    if (speed > 0) {
        // 正向转动：AIN1高电平，AIN2低电平，PWM占空比为speed
        DL_GPIO_setPins(AIN1_PORT, AIN1_GPIO_AIN_1_PIN);
        DL_GPIO_clearPins(AIN2_PORT, AIN2_GPIO_AIN_2_PIN);
        DL_TimerG_setCaptureCompareValue(PWM_Right_left_INST, speed, GPIO_PWM_Right_left_C0_IDX);
    } 
    else if (speed < 0) {
        // 反向转动：AIN2高电平，AIN1低电平，PWM占空比为-speed（绝对值）
        DL_GPIO_setPins(AIN2_PORT, AIN2_GPIO_AIN_2_PIN);
        DL_GPIO_clearPins(AIN1_PORT, AIN1_GPIO_AIN_1_PIN);
        DL_TimerG_setCaptureCompareValue(PWM_Right_left_INST, -speed, GPIO_PWM_Right_left_C0_IDX);
    } 
    else {
        // 速度为0：停止电机（双引脚均低电平，PWM占空比0）
        DL_GPIO_clearPins(AIN1_PORT, AIN1_GPIO_AIN_1_PIN);
        DL_GPIO_clearPins(AIN2_PORT, AIN2_GPIO_AIN_2_PIN);
        DL_TimerG_setCaptureCompareValue(PWM_Right_left_INST, 0, GPIO_PWM_Right_left_C0_IDX);
    }
}

// speed 范围在-10000 到 10000
void set_2motorspeed(int speed)
{
    // 限制速度范围
    if (speed > 10000) speed = 10000;
    if (speed < -10000) speed = -10000;
    
    // 控制电机方向和PWM
    if (speed > 0) {
        // 正向转动：BIN1高电平，BIN2低电平，PWM占空比为speed
        DL_GPIO_setPins(BIN1_PORT, BIN1_GPIO_BIN_1_PIN);
        DL_GPIO_clearPins(BIN2_PORT, BIN2_PIN_3_PIN);
        DL_TimerG_setCaptureCompareValue(PWM_Right_left_INST, speed, GPIO_PWM_Right_left_C1_IDX);
    } 
    else if (speed < 0) {
        // 反向转动：BIN2高电平，BIN1低电平，PWM占空比为-speed（绝对值）
        DL_GPIO_setPins(BIN2_PORT, BIN2_PIN_3_PIN);
        DL_GPIO_clearPins(BIN1_PORT, BIN1_GPIO_BIN_1_PIN);
        DL_TimerG_setCaptureCompareValue(PWM_Right_left_INST, -speed, GPIO_PWM_Right_left_C1_IDX);
    }
    else {
        // 速度为0：停止电机（双引脚均低电平，PWM占空比0）
        DL_GPIO_clearPins(BIN1_PORT, BIN1_GPIO_BIN_1_PIN);
        DL_GPIO_clearPins(BIN2_PORT, BIN2_PIN_3_PIN);
        DL_TimerG_setCaptureCompareValue(PWM_Right_left_INST, 0, GPIO_PWM_Right_left_C1_IDX);
    }
}

void car_stop()
{
        DL_GPIO_setPins(BIN1_PORT, BIN1_GPIO_BIN_1_PIN);
        DL_GPIO_setPins(BIN2_PORT, BIN2_PIN_3_PIN);

}